import React, { CSSProperties } from 'react';
import { Image } from "@tarojs/components";

const styles = {
  img: {
    width: 50,
    height: 50,
  },
};

interface IState {
  index: number;
}

interface IProps {
  images: string[];
  style?: CSSProperties;
  animationTim?: number; // 多少时间切换一次图片,默认700ms
}

class FrameImage extends React.Component<IProps, IState> {
  state = {
    index: 0,
  };

  timer: any;

  componentDidMount() {
    const { images, animationTim = 700 } = this.props;
    this.timer = setInterval(() => {
      const { index } = this.state;
      const newIndex = (index + 1) % images.length;
      this.setState({ index: newIndex });
    }, animationTim);
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  render() {
    const { images, style } = this.props;
    const { index } = this.state;
    return (
      <Image
        style={{
          ...styles.img,
          ...style,
        }}
        src={images[index]}
      />
    );
  }
}

export default FrameImage;
